<template>
  <div style="width: 100%; background: #fff; height: calc(100vh - 58px)">
    <!-- 搜索区域 -->
    <div
      style="display: flex; height: 100px; padding: 10px; flex-wrap: wrap"
      v-show="isSearch"
      class="animate__animated animate__fadeIn"
    >
      <div style="margin-left: 10px; padding: 10px 0">
        <span style="margin-right: 8px; font-weight: 00">角色名称</span>
        <el-input
          style="width: 180px"
          size="default"
          placeholder="请输入角色名称"
          v-model="searchForm.name"
        ></el-input>
      </div>
      <div style="margin-left: 10px; padding: 10px 0">
        <span style="margin-right: 8px; font-weight: 00">权限字符</span>
        <el-input
          style="width: 180px"
          size="default"
          placeholder="请输入权限字符"
          v-model="searchForm.grade"
          @blur="isEng"
          :class="{ active: ruleGrade }"
        ></el-input
        ><span style="color: red; font-size: 11px" v-if="ruleGrade">权限字符只能是英文！</span>
      </div>
      <div style="margin-left: 10px; padding: 10px 0">
        <span style="margin-right: 8px; font-weight: 00">状态</span>
        <el-select
          v-model="searchForm.status"
          clearable
          placeholder="请选择状态"
          style="width: 180px"
        >
          <el-option
            v-for="item in statusList"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </el-select>
      </div>
      <div style="margin-left: 10px; padding: 10px 0">
        <span style="margin-right: 8px; font-weight: 00">创建时间</span>
        <el-date-picker
          v-model="searchForm.createTime"
          type="datetime"
          placeholder="选择创建日期"
          size="default"
          style="width: 180px"
        />
      </div>
      <div style="margin-left: 10px; padding: 10px 0">
        <el-button type="primary" @click="search"
          ><el-icon><Search /></el-icon>搜索</el-button
        >
        <el-button @click="reset"
          ><el-icon><Refresh /></el-icon>重置</el-button
        >
      </div>
    </div>
    <div>
      <!-- 操作区域 -->
      <div style="height: 40px; padding: 10px; display: flex; justify-content: space-between">
        <div style="width: 70%">
          <el-button type="primary" :icon="Plus" plain size="small" @click="addRole"
            >新增</el-button
          >
          <el-button type="success" :icon="Edit" plain size="small">修改</el-button>
          <el-button type="danger" :icon="Delete" plain size="small" @click="deleteRole(null, 0)"
            >删除</el-button
          >
        </div>
        <div>
          <el-button
            style="border-radius: 50%; width: 30px; height: 30px"
            @click="isSearch = !isSearch"
            title="搜索"
            ><el-icon><Search /></el-icon
          ></el-button>
          <el-button
            style="border-radius: 50%; width: 30px; height: 30px; margin-right: 20px"
            @click="flush"
            title="刷新"
            ><el-icon><Refresh /></el-icon
          ></el-button>
        </div>
      </div>
      <!-- 数据展示 -->
      <div>
        <el-table
          size="small"
          :data="rolesList"
          style="width: 100%"
          stripe
          max-height="400"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" :selectable="handlerSelect" />
          <el-table-column type="index" width="50"  label="编号" align="center" />
          <el-table-column prop="name" label="角色名称" width="180" />
          <el-table-column prop="grade" label="权限字符" />
          <el-table-column label="状态" align="center">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                class="ml-2"
                :active-value="1"
                :inactive-value="0"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="创建时间" width="200">
            <template #default="scope">
              <div>{{ titleUtil.formatDate(scope.row.createTime) }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="240" align="center">
            <template #default="scope">
              <div v-if="scope.row.grade !== 'admin'">
                <el-button size="small" type="text" @click="editRole(scope.row)"
                  ><el-icon><Edit /></el-icon>修改</el-button
                >
                <el-button size="small" type="text" @click="deleteRole(scope.row.id, 1)" style="margin-right:10px"
                  ><el-icon><Delete /></el-icon>删除</el-button
                >

                <el-dropdown size="small">
                  <el-button size="small" type="text">
                    <el-icon><DArrowRight /></el-icon>更多
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item>
                        <span style="font-size: 10px" @click="toAdmin(scope.row.id)"
                          ><el-icon><User /></el-icon>分配用户</span
                        >
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
  <AdminRoleDialog ref="adminRole" @watch-form="flush"></AdminRoleDialog>
  <AdminList ref="adminList" @flush="flush"></AdminList>
</template>

<script setup>
import request from '@/util/request'
import { ElNotification } from 'element-plus'
import { onMounted, ref } from 'vue'
import titleUtil from '@/util/titleUtil'
import { Delete, Edit, Plus } from '@element-plus/icons-vue'
import AdminRoleDialog from '@/components/AdminRoleDialog.vue'
import AdminList from '@/components/AdminList.vue'

const isSearch = ref(true)
const adminList = ref()
const adminRole = ref()
const rolesList = ref([])
const selectRoles = ref([])
const menuList = ref([])
const admins = ref([])
const userList = ref([])

const statusList = ref([
  { id: 0, label: '禁用' },
  { id: 1, label: '启用' }
])

const ruleGrade = ref(false)

const searchForm = ref({
  name: '',
  grade: '',
  status: null,
  createTime: null
})

const addRole = () => {
  console.log('执行了')
  adminRole.value.open(null, menuList.value)
}

const handleSelectionChange = (val) => {
  selectRoles.value = val
  console.log(selectRoles.value)
}

const isEng = () => {
  const grade = titleUtil.isEnglish(searchForm.value.grade)
  console.log(grade)

  if (!grade) {
    ruleGrade.value = true
  } else {
    ruleGrade.value = false
  }
}

const getUsers = (id) => {
  request
    .get(`/admin/user/list?id=${id}`)
    .then((res) => {
      console.log('获取的用户数据', res.data)
      userList.value = res.data
    })
    .catch((err) => {
      if (err.response) {
        console.error(err.message)
        // ElMessage.error('出错了', err.message)
        ElNotification({
          title: 'Error',
          message: err.message,
          type: 'error'
        })
      } else {
        ElNotification({
          title: 'Error',
          message: '网络错误',
          type: 'error'
        })
      }
    })
}

const toAdmin = (id) => {
  // 获取角色id对应的管理员账号
  const arr = admins.value.filter((item) => item.roleId === id)
  console.log('过滤的数组', arr,id)
  adminList.value.open(userList.value, arr,id)
}

const handlerSelect = (row, index) => {
  if (row.id === 1) {
    return false
  } else {
    return true
  }
}

const deleteRole = (item, type) => {
  let ids = []
  if (type === 1) {
    ids.push(item)
  } else {
    ids = selectRoles.value.map((item) => item.id)
  }

  console.log('上传id', ids)

  if (ids.length <= 0) {
    ElNotification.warning('抱歉，你没有选中角色')
    return
  }

  request
    .post('/admin/role/delete', ids)
    .then((res) => {
      ElNotification.success('操作成功')
      selectRoles.value = []
      flush()
    })
    .catch((err) => {
      if (err.response) {
        console.error(err.message)
        ElNotification({
          title: 'Error',
          message: err.message,
          type: 'error'
        })
      } else {
        ElNotification({
          title: 'Error',
          message: '网络错误',
          type: 'error'
        })
      }
    })
}

const editRole = (item) => {
  adminRole.value.open(item, menuList.value)
}

const getAdminList = () => {
  request
    .get('/admin/list')
    .then((res) => {
      console.log('获取成功：', res)
      admins.value = res.data
    })
    .catch((err) => {
      if (err.response) {
        console.error(err.message)
        ElNotification({
          title: 'Error',
          message: err.message,
          type: 'error'
        })
      } else {
        ElNotification({
          title: 'Error',
          message: '网络错误',
          type: 'error'
        })
      }
    })
}

const search = () => {
  if (
    searchForm.value.name === '' &&
    searchForm.value.grade === '' &&
    searchForm.value.status === null &&
    searchForm.value.createTime == null
  ) {
    ElNotification.warning('搜索条件不能为空哦，亲')
    return
  }
  request
    .post('/admin/role/search', searchForm.value)
    .then((res) => {
      console.log('获取的搜索结果', res)
      rolesList.value = res.data
    })
    .catch((err) => {
      if (err.response) {
        console.error(err.message)
        ElNotification({
          title: 'Error',
          message: err.message,
          type: 'error'
        })
      } else {
        ElNotification({
          title: 'Error',
          message: '网络错误',
          type: 'error'
        })
      }
    })
}

const reset = () => {
  searchForm.value = {
    name: '',
    grade: '',
    status: null,
    createTime: null
  }
}

const getRolesList = () => {
  request
    .get('/admin/role/list')
    .then((res) => {
      console.log('获取成功：', res)
      rolesList.value = res.data
    })
    .catch((err) => {
      if (err.response) {
        console.error(err.message)
        ElNotification({
          title: 'Error',
          message: err.message,
          type: 'error'
        })
      } else {
        ElNotification({
          title: 'Error',
          message: '网络错误',
          type: 'error'
        })
      }
    })
}

const getMenuList = () => {
  request
    .get('/admin/menu/list')
    .then((res) => {
      console.log('获取成功：', res)
      menuList.value = res.data
    })
    .catch((err) => {
      if (err.response) {
        console.error(err.message)
        ElNotification({
          title: 'Error',
          message: err.message,
          type: 'error'
        })
      } else {
        ElNotification({
          title: 'Error',
          message: '网络错误',
          type: 'error'
        })
      }
    })
}

const flush = () => {
  getRolesList()
  getAdminList()
}

onMounted(() => {
  getRolesList()
  getMenuList()
  getAdminList()
  getUsers(0)
})
</script>

<style scoped>
.active {
  border: rgb(255, 47, 0) 1px solid;
  border-radius: 5px;
}
</style>
